package com.nothing.service.run;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import javax.imageio.ImageIO;

import com.nothing.controller.ShowCheckFaceController;
import com.nothing.controller.WebCamPreviewController;
import com.nothing.domain.UserFaceImg;
import com.nothing.domain.UserFaceInfo;
import com.nothing.dto.FaceSearchResult;
import com.nothing.service.FaceEngineService;
import com.nothing.service.UserFaceInfoService;
import com.nothing.view.FxmlView;
import com.xiaoleilu.hutool.date.DateUtil;

import cn.hutool.core.collection.CollectionUtil;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
/**
 * 
 * @author shíQíang㊚
 *
 */
public class CheckDbFace implements Runnable {

	private AtomicInteger count;
	private ImageView faceOne;
	private ImageView faceTwo;
	private ImageView faceThree;
	private ImageView faceFour;
	private ImageView faceFive;
	private FaceEngineService faceEngineService;
	private UserFaceInfoService userFaceInfoService;
	
	private WebCamPreviewController webCam;
	private List<UserFaceImg> data;
	public CheckDbFace(List<UserFaceImg> data, WebCamPreviewController webCam,
			FaceEngineService faceEngineService, UserFaceInfoService userFaceInfoService, AtomicInteger count,
			ImageView faceOne, ImageView faceTwo, ImageView faceThree, ImageView faceFour, ImageView faceFive) {
		this.data = data;
		this.webCam = webCam;
		this.faceEngineService = faceEngineService;
		this.userFaceInfoService = userFaceInfoService;
		this.count = count;
		this.faceOne = faceOne;
		this.faceTwo = faceTwo;
		this.faceThree = faceThree;
		this.faceFour = faceFour;
		this.faceFive = faceFive;
	}
 
//	private List<UserFaceImg> getData() {
//		try {
//			if (CollectionUtil.isEmpty(data)) {
//				synchronized(CheckDbFace.class){
//					data = userFaceImgService.selectList(new EntityWrapper<UserFaceImg>().eq("state", "0"));
//					if (CollectionUtil.isEmpty(data)) {
//						synchronized (CheckDbFace.class) {
//							data = userFaceImgService.selectList(new EntityWrapper<UserFaceImg>().eq("state", "0"));
//						} 
//					}
//					if(CollectionUtil.isNotEmpty(data)){
//						data.stream().forEach(img -> img.setState(1));
//						userFaceImgService.updateBatchById(data);
//					} 
//				}
//			} 
//		} catch (Exception e) {
//			 
//		}
//		return data;
//	}

	@Override
	public void run() {
		try {
			doCheck();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doCheck() {
		
		for (UserFaceImg img : data) {
			try (ByteArrayInputStream in = new ByteArrayInputStream(img.getImg());) {
				BufferedImage image = ImageIO.read(in);
				List<FaceSearchResult> usersInDb = faceEngineService.findUsersByFaces(image,
						WebCamPreviewController.groupId);

				if (CollectionUtil.isNotEmpty(usersInDb)) {
					// WebCamPreviewController.toCheck = false;
					doUpdateUserInfo(usersInDb);
					showFace(image, usersInDb);
					// 弹出
					// checkSuccess(usersInDb, hasCheckedFace);
				}
				image.flush();
			} catch (Exception e) {
				// TODO: handle exception
			} 
		}
		System.out.println("检验-数据库-人脸-数据");
		data.clear();
	}

	private void doUpdateUserInfo(List<FaceSearchResult> usersInDb) {
		List<UserFaceInfo> users = userFaceInfoService
				.selectBatchIds(usersInDb.stream().map(search -> search.getId()).collect(Collectors.toList()));
		if (CollectionUtil.isEmpty(users)) {
			return;
		}
		users.stream().forEach(user -> {
			user.setChecked(1);
			user.setUpdateTime(DateUtil.now());
			faceEngineService.delFaceFromCache(user.getGroupId(), user.getId());
		});
		userFaceInfoService.updateBatchById(users);
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				webCam.search();
			}
		});
	}

	private void drow(BufferedImage bufImage, String name, String age, String gender, String group) {
		Graphics2D g = bufImage.createGraphics();
		g.setBackground(Color.white);
		g.drawImage(bufImage, 0, 0, null);
		Font font = new Font("微软雅黑", Font.BOLD, 25);
		g.setFont(font);
		g.drawString("姓名:" + name, 100, 100);
		g.drawString("性别:" + gender, 100, 200);
		g.drawString("年龄:" + age, 100, 300);
		g.drawString("分组:" + group, 100, 400);
		g.dispose();
	}

	private void showFace(BufferedImage data, List<FaceSearchResult> users) {
		String name = "";
		String age = "";
		String gender = "";
		String group = "";
		if (CollectionUtil.isNotEmpty(users)) {
			for (FaceSearchResult user : users) {
				UserFaceInfo userInDb = userFaceInfoService.findByFaceId(user.getFaceId());
				name += userInDb.getName() + "|";
				age += userInDb.getAge() + "|";
				gender += (userInDb.getGender().equals("0") ? "女" : "男") + "|";
				group += " " + "|";
			}
		}

		int imgCount = count.incrementAndGet();
		drow(data, name, age, gender, group);
		WritableImage hasCheckedFace = SwingFXUtils.toFXImage(data, null);

		if (imgCount % 5 == 0) {
			faceOne.setImage(hasCheckedFace);
		} else if (imgCount % 5 == 1) {
			faceTwo.setImage(hasCheckedFace);
		} else if (imgCount % 5 == 2) {
			faceThree.setImage(hasCheckedFace);
		} else if (imgCount % 5 == 3) {
			faceFour.setImage(hasCheckedFace);
		} else if (imgCount % 5 == 4) {
			faceFive.setImage(hasCheckedFace);
		}
		data.flush();
	}

	@SuppressWarnings("unused")
	private void checkSuccess(List<FaceSearchResult> users, Image findImg) {
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				String name = "";
				String age = "";
				String gender = "";
				String group = "";

				if (CollectionUtil.isNotEmpty(users)) {
					for (FaceSearchResult user : users) {
						UserFaceInfo userInDb = userFaceInfoService.findByFaceId(user.getFaceId());
						name += userInDb.getName() + "|";
						age += userInDb.getAge() + "|";
						gender += (userInDb.getGender().equals("0") ? "女" : "男") + "|";
						group += " " + "|";
					}
				}

				Stage stage = new Stage();

				FXMLLoader loader = new FXMLLoader(getClass().getResource(FxmlView.SHOW.getFxmlFile()));

				loader.setController(new ShowCheckFaceController(findImg, name, age, gender, group));

				try {

					stage.setScene(new Scene(loader.load()));
					stage.setTitle(FxmlView.SHOW.getTitle());
					stage.show();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
}